package com.zto.sch.other.yuxiaoer;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.ArrayList;

/**
 * @program: sch-diy-parent
 * @description: 寓小二面试题，判断一个数组是否在另一个数组中
 * @author: sch
 * @create: 2021-01-16 10:55
 **/
@Slf4j
public class TestArrTwo {

    public static void main(String[] args) {
        int sourArr[] = {9, 3, 5, 4, 6, 4, 3, 5};
        int targetArr[] = {5, 4, 6};
//        int index = getTargetArrayIndex(sourArr, targetArr);
//
//        log.info("数据targetArr在sourArr的起始位置是:[{}]", index);
    }

    @Test
    public void test() {
        int sourArr[] = {9, 3, 5, 4, 6, 4, 3, 5};
        int targetArr[] = {5, 4, 6};
        int index = getTargetArrayIndex(sourArr, targetArr);

        log.info("数据targetArr在sourArr的起始位置是:[{}]", index);
    }

    private int getTargetArrayIndex(int[] sourArr, int[] targetArr) {
        //1,校验
        if (sourArr == null
                || targetArr == null) {
            throw new RuntimeException("参数有误会");
        }

        //2,判断是否存在
        boolean isExit = isExit(sourArr, targetArr, sourArr.length, targetArr.length);
        //找到targetArr在sourArr的起始位置
        if (isExit) {
            //3,计算索引
            return getIndex(sourArr, targetArr);
        }


        return -1;
    }

    private int getIndex(int[] sourArr, int[] targetArr) {
        //找到两个数组第一次相同的元素
        int firstEqualVal = getEqualKey(sourArr, targetArr);


        //找到这个元素在sourArr的索引位置
        return indexOfArr(sourArr, firstEqualVal);
    }


    public static int indexOfArr(int[] arr, int value) {
        //校验
        if (arr == null) {
            throw new RuntimeException("参数有误");
        }

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;
            }
        }

        return -1;
    }

    private int getEqualKey(int[] sourArr, int[] targetArr) {
        for (int source : sourArr) {
            for (int target : targetArr) {
                if (source == target) {
                    return target;
                }
            }
        }
        //抛异常
        throw new RuntimeException("信息不存在");
    }


    boolean isExit(int sourArr[], int targetArr[], int m, int n) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            if (!arrayList.contains(sourArr[i])) {
                arrayList.add(sourArr[i]);
            }
        }

        for (int i = 0; i < n; i++) {
            if (!arrayList.contains(targetArr[i])) {
                return false;
            }
        }

        return true;
    }
}
